<template>
  <div class="sn-container">
    <div class="container">
      <el-row>
        <el-col :xl="24" :lg="24" style="border-right: 1px solid #dcdfe6">
          <div style="padding-left: 10px">
            <div class="handle-box">
              <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item
                  key="status"
                  label=""
                  prop="status"
                >
                  <!-- 状态，2：已发送，1：删除，0：草稿 -->
                  <el-radio-group v-model="queryParams.status" style="margin-bottom: 30px">
                    <el-radio-button value="">全部消息</el-radio-button>
                    <el-radio-button value="2">已发送</el-radio-button>
                    <el-radio-button value="1">删除</el-radio-button>
                    <el-radio-button value="0">草稿</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  key="condition"
                  label=""
                  prop="condition"
                >
                  <el-input
                    v-model="queryParams.condition"
                    placeholder="搜索标题/消息内容..."
                  />
                </el-form-item>
                <el-button @click="fetchMessageData" type="primary" >查询</el-button>
                <el-button @click="openAddDialog" type="primary" :icon="Plus" >新建消息</el-button>
              </el-form>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
              <el-table-column
                key="theme"
                prop="theme"
                label="标题"
                width="auto"
              >
              <template #default="scope">
                <div>
                  <div style="font-size: 16px; color: #000; font-weight: bold;">
                    {{ scope.row.theme }}
                  </div>
                  <div v-html="scope.row.msg" />
                </div>
              </template>
              </el-table-column>
              <el-table-column
                key="status"
                prop="status"
                label="状态"
                width="120"
              >
                <template #default="scope">
                  <!-- 2：已发送，1：删除，0：草稿 -->
                  <el-tag v-if="scope.row.status === 0" type="warning">草稿</el-tag>
                  <el-tag v-else-if="scope.row.status === 1" type="danger">删除</el-tag>
                  <el-tag v-else-if="scope.row.status === 2" type="success">已发送</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                key="notifyGroupList"
                prop="notifyGroupList"
                label="接收人"
              >
                <template #default="scope">
                  <el-tag v-for="item in scope.row.notifyGroupList" :key="item.id">{{ item.notifyGroupName }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                key="updateTime"
                prop="updateTime"
                label="操作时间"
              />
              <el-table-column label="操作" width="300" fixed="right">
                <template #default="scope">
                  <el-button text :icon="Edit" @click="handleEdit(scope.row)">
                    编辑
                  </el-button>
                  <el-button text :icon="Delete" class="red" @click="handleDelete(scope.row)">
                    删除
                  </el-button>
                  </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                background
                layout="total, prev, pager, next"
                :current-page="queryParams.pageNum"
                :page-size="queryParams.pageSize"
                :total="pageTotal"
                @current-change="handlePageChange"
              ></el-pagination>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 新增 -->
    <el-dialog title="新建消息" v-model="addVisible" width="50%" :destroy-on-close="true">
      <el-form :model="snForm" ref="addFormRef">
        <el-form-item
          key="theme"
          label="消息标题"
          prop="theme"
        >
        <el-input
            v-model="snForm.theme"
            placeholder="请输入消息标题"
            clearable
          />
        </el-form-item>
        <el-form-item
          key="msgType"
          label="消息类型"
          prop="msgType"
        >
          <el-select
            v-model="snForm.msgType"
            placeholder="请选择消息类型"
          >
            <el-option
              v-for="option in msgTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          key="msg"
          label="消息内容"
          prop="msg"
        >
        <el-input
            v-model="snForm.msg"
            placeholder="请输入消息内容"
            type="textarea"
            clearable
          />
        </el-form-item>
        <el-form-item
          key="notifyGroupList"
          label="接收人"
          prop="notifyGroupList"
          class="org-person"
        >
          <!-- <el-tabs v-model="activateTab" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="按部门" name="org">
              <el-tree
                style="max-width: 600px"
                :props="props"
                :data="orgList"
                show-checkbox
                @check-change="handleCheckChange"
              />
            </el-tab-pane>
            <el-tab-pane label="按个人" name="person">
              <el-checkbox-group>
                <el-checkbox value="Online activities" name="type">
                  Online activities
                </el-checkbox>
                <el-checkbox value="Promotion activities" name="type">
                  Promotion activities
                </el-checkbox>
                <el-checkbox value="Offline activities" name="type">
                  Offline activities
                </el-checkbox>
                <el-checkbox value="Simple brand exposure" name="type">
                  Simple brand exposure
                </el-checkbox>
              </el-checkbox-group>
            </el-tab-pane>
          </el-tabs> -->
          <!-- 组织架构选择弹出框 -->
          <OrgSelect
            v-if="isLoadedOrgList"
            append-to-body
            :visible="isOrgSelectShow"
            :activeRoleId="activeRoleId"
            :tab-type="tabType"
            :father-org-list="orgList"
            @on-cancel="handleOrgSelectCancel"
            @org-change="orgChange"
            @on-submit="handleOrgSelectSubmit"
          />
        </el-form-item>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="addVisible = false">取 消</el-button>
					<el-button @click="saveMsgData('add', 0)">存为草稿</el-button>
          <el-button type="primary" @click="saveMsgData('add', 2)">发送消息</el-button>
				</span>
      </template>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="编辑" v-model="editVisible" width="50%" :destroy-on-close="true">
      <el-form :model="snForm" ref="queryForm">
        <el-form-item
          key="theme"
          label="消息标题"
          prop="theme"
        >
        <el-input
            v-model="snForm.theme"
            placeholder="请输入消息标题"
            clearable
          />
        </el-form-item>
        <el-form-item
          key="msgType"
          label="消息类型"
          prop="msgType"
        >
          <el-select
            v-model="snForm.msgType"
            placeholder="请选择消息类型"
          >
            <el-option
              v-for="option in msgTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          key="msg"
          label="消息内容"
          prop="msg"
        >
        <el-input
            v-model="snForm.msg"
            placeholder="请输入消息内容"
            type="textarea"
            clearable
          />
        </el-form-item>
        <el-form-item
          key="notifyGroupList"
          label="接收人"
          prop="notifyGroupList"
          class="org-person"
        >
          <OrgSelect
            v-if="isLoadedOrgList"
            append-to-body
            :visible="isOrgSelectShow"
            :activeRoleId="activeRoleId"
            :tab-type="tabType"
            :father-org-list="orgList"
            :selected-user-ids-info="snForm.notifyGroupList"
            @on-cancel="handleOrgSelectCancel"
            @org-change="orgChange"
            @on-submit="handleOrgSelectSubmit"
          />
        </el-form-item>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="editVisible = false">取 消</el-button>
					<el-button @click="saveMsgData('update', 0)">存为草稿</el-button>
          <el-button type="primary" @click="saveMsgData('update', 2)">发送消息</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
  import {reactive, ref, onMounted, watch} from 'vue';
  import {ElMessage, ElMessageBox} from 'element-plus';
  import {Delete, Edit, Plus} from '@element-plus/icons-vue';
  import { getMessageList, addMessageList, getMessageDetail, updateMessage, deleteMessage } from "../api/message";
  import {getOrganizationTree} from "../api/organization";
  import OrgSelect, {OrgSelectedData} from "../components/OrgSelectInput.vue";
  import {getRoleUserList} from "../api/role";
  import type { FormInstance, FormRules } from 'element-plus'
  import {useBasicStore} from "../store/basic";

  interface TableItem {
    id: number;
    name: string;
    location: string;
    time: string;
    description: string;
    level: string;
  }

  const snListColum = ref<any>({});

  const userinfoStore = useBasicStore();
  const userinfo = userinfoStore.userinfo;
  const username: string | null = userinfo.username;
  const isLoadedOrgList = ref(false);
  const addFormRef = ref<FormInstance>()
  const msgTypeOptions  = ref<any[]>([
    // ：国铁通知，2：地铁通知，3：通用通知，4：部门内部通知
    { label: '国铁通知', value: 1 },
    { label: '地铁通知', value: 2 },
    { label: '通用通知', value: 3 },
    { label: '部门内部通知', value: 4 }
  ]);
  const tabType = ref<any>('org');

  const isOrgSelectShow = ref(true);

  const snForm = ref<any>({});

  const query = reactive({
    pageNum: 1,
    pageSize: 10
  });

  const userQuery = reactive({
    username: '',
    state: '',
    pageIndex: 1,
    pageSize: 10
  });

  const activeRoleId = ref<number>(1);

  const tableData = ref<TableItem[]>([]);
  const pageTotal = ref(0);
  const addVisible = ref(false);
  const editVisible = ref(false);
  const fileData = ref<any>(null);
  const uploadRef = ref();
  const orgList = ref<any>(null);
  let count = 1
  const props = {
    label: 'name',
    children: 'children',
  }

  const activateTab = ref('org')

  const handleOrgSelectCancel = () => {
    isOrgSelectShow.value = false;
  }

  const getUserData = (roleId: number) => {
    getRoleUserList(roleId, {
      page: userQuery.pageIndex,
      size: userQuery.pageSize,
      username: userQuery.username || undefined,
      state: userQuery.state || undefined,
    }).then(res => {
      tableData.value = res.data.list;
      pageTotal.value = res.data.total;
    });
  }

  const handleOrgSelectSubmit = (p: OrgSelectedData) => {
    console.log("handleOrgSelectSubmit is ", p);
    let userIds = new Array();
    p.selected.forEach((orgItem: any) => {
      userIds.push({
        notifyGroup: orgItem.id,
        notifyGroupType: "2",
        notifyGroupName: orgItem.username
      });
    });
    console.log("userIds is ", userIds);
    snForm.value.notifyGroupList = userIds;
  }

  const orgChange = (p: any) => {
    console.log("orgChange is ", p);
    let orgIds = new Array();
    p.selected.forEach((orgItem: any) => {
      orgIds.push({
        notifyGroup: orgItem.id,
        notifyGroupType: "0",
        notifyGroupName: orgItem.name
      });
    });
    console.log("orgIds is ", orgIds);
    snForm.value.notifyGroupList = orgIds;
  }

  const loadNode = (node: any, resolve: any) => {
    if (node.level === 0) {
      return resolve([{ name: 'Root1' }, { name: 'Root2' }])
    }
    if (node.level > 3) return resolve([])

    let hasChild = false
    if (node.data.name === 'region1') {
      hasChild = true
    } else if (node.data.name === 'region2') {
      hasChild = false
    } else {
      hasChild = Math.random() > 0.5
    }

    setTimeout(() => {
      let data: any = []
      if (hasChild) {
        data = [
          {
            name: `zone${count++}`,
          },
          {
            name: `zone${count++}`,
          },
        ]
      } else {
        data = []
      }

      resolve(data)
    }, 500)
  }
  // 初始化表单数据
  const initForm = () => {
    const formData: any = {};
    
    if (snListColum.value.properties && Array.isArray(snListColum.value.properties)) {
      snListColum.value.properties.forEach((property: any) => {
        switch (property.type) {
          case 'select':
            formData[property.name] = property.options?.[0]?.value || '';
            break;
          case 'daterange':
            formData[property.name] = [];
            break;
          case 'datetime':
            formData[property.name] = '';
            break;
          default:
            formData[property.name] = '';
        }
      });
    }
    
    return formData;
  };

  // 初始化查询参数
  const initQueryParams = () => {
    const params: any = {
      pageNum: 1,
      pageSize: 10,
      msgType: "",
      msg: "",
      theme: "",
      status: "",
      condition: ""
    };
    return params;
  };

  const queryParams = reactive(initQueryParams());

  // 保存数据
  const saveMsgData = async (saveType: string, msgStatus: number) => {
    try {
      console.log("snForm is ", snForm.value);
      snForm.value.createUserAccount = username;
      snForm.value.status = msgStatus;
      const newFormData = JSON.parse(JSON.stringify(snForm.value));
      let snRes: any;
      if (saveType === 'add') {
        delete newFormData.id;
        snRes = await addMessageList(snForm.value);
      } else {
        snRes = await updateMessage(newFormData);
      }

      console.log("snRes is ", snRes);
      ElMessage.success('保存成功');
      addVisible.value = false;
      editVisible.value = false;
      await fetchMessageData(); // 重新加载表格数据
    } catch (error) {
      console.error("保存失败:", error);
      ElMessage.error('保存失败');
    }
  }

  // 获取表格数据
  const fetchMessageData = async () => {
    try {
      // const params = initQueryParams();
      console.log("params is ", queryParams);
      const res = await getMessageList(queryParams);
      console.log("getMessageList 获取数据成功:", res);
      tableData.value = res.data.data.records;
      pageTotal.value = res.data.data.total;
    } catch (error) {
      console.error("获取数据失败:", error);
      ElMessage.error('获取数据失败');
    }
  };

  // 获取组织架构
  const reqOrgList = async () => {
    const res = await getOrganizationTree({
      parentId: 1,
    })
    orgList.value = res.data;
    isLoadedOrgList.value = true;
    console.log("orgList is ", res.data);
  }
  // 组件挂载时初始化数据
  onMounted(async () => {
    // 获取消息列表
    fetchMessageData();
    await reqOrgList();
  });

  // 查询操作
  const handleSearch = async () => {
    query.pageNum = 1;
    await fetchMessageData();
  };

  // 分页导航
  const handlePageChange = async (val: number) => {
    queryParams.pageNum = val;
    await fetchMessageData();
  };

  // 处理编辑
  const handleEdit = async (row: any) => {
    const resDetail = await getMessageDetail(row.id);
    console.log("resDetail is ", resDetail);
    const resData = resDetail.data.data;
    activeRoleId.value = resData.roleId;
    if (resData.notifyGroupList.length > 0) {
      const gtype = resData.notifyGroupList[0].notifyGroupType;
      if (gtype == 0) {
        tabType.value = 'org';
      } else if (gtype == 2) {
        tabType.value = 'person';
      }
      console.log("gtype is ", gtype, " tabType.value is ", tabType.value);
    }
    snForm.value = resDetail.data.data;
    // 填充表单数据
    Object.keys(snForm.value).forEach(key => {
      if (resDetail.data.data[key] !== undefined) {
        snForm.value[key] = resDetail.data.data[key];
      }
    });
    editVisible.value = true;
  };

  // 处理删除
  const handleDelete = async (row: any) => {
    try {
      await ElMessageBox.confirm('确定要删除吗？', '提示', {
        type: 'warning'
      });
      // 这里调用删除API
      await deleteMessage(row.id);
      ElMessage.success('删除成功');
      await fetchMessageData(); // 重新加载数据
    } catch (error) {
      console.log("取消删除");
    }
  };

  // 打开新增对话框
  const openAddDialog = (formEl: any) => {
    // 重置表单数据
    Object.assign(snForm.value, initForm());
    // if (!formEl) return
    // formEl.resetFields();

    snForm.value.theme = "";
    snForm.value.notifyGroupList = [];
    snForm.value.msg = "";
    addVisible.value = true;
  };
  watch(() => queryParams.status, async (newVal: any, oldVal) => {
    console.log("newVal is ", newVal);
    // selectedUserIds.value = JSON.parse(JSON.stringify(newVal));
    await fetchMessageData();
  }, {
    deep: true,
    immediate: true
  });
</script>

<style lang="scss" scoped>
.sn-container {
  :deep(.el-select) {
    min-width: 120px;
  }
  :deep(.el-form) {
    .org-person {
      .el-form-item__content {
        padding: 10px;
        border: solid 1px #dcdfe6
      }
    }
  }
  .container {
    :deep(.el-form-item__content) {
      .upload-area {
        .el-upload {
          .el-button {
            margin: 0 10px;
          }
        }
        .el-upload-list {
          display: none;
        }
      }
    }
    :deep(.handle-box) {
      .el-form {
        .el-form-item {
          margin-bottom: 0;
          .el-form-item__content {
            .el-radio-group{
              margin-bottom: 0 !important;
            }
            .el-input {
              width: 400px;
            }
          }
        }
      }
    }
  }
  .el-overlay {
    .el-overlay-dialog {
      .el-dialog {
        .el-dialog__body {
          .el-form {
            .el-form-item {
              :deep(.el-form-item__label) {
                width: 100px;
              }
            }
          }
        }
      }
    }
  }
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #F56C6C;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

</style>
